package com.penghaisoft.microwms.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

/**
 * i18n多语言 配置 by qihong
 */
@Slf4j
@Configuration
@ConditionalOnExpression("!'${spring.messages.basename:}'.isEmpty()")
public class I18nConfiguration extends WebMvcConfigurerAdapter {

	@Value(value = "${spring.messages.basename}")
	private String basename;
	
	@Bean(name = "messageSource")
	public ResourceBundleMessageSource getMessageResource(){
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		messageSource.setBasename(basename);
		return messageSource;
	}
	
	/**
	 * 默认国际语言
	 */
	@Bean
	public LocaleResolver localeResolver() {
		SessionLocaleResolver slr = new SessionLocaleResolver();
		//slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
		slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
		return slr;
	}

	/**
	 * 国际化更改拦截
	 */
	@Bean
	public LocaleChangeInterceptor localeChangeInterceptor() {
		LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
		lci.setParamName("lang");
		return lci;
	}

	/**
	 * 添加拦截器
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(localeChangeInterceptor());
		log.info("wms-common-----------Common-i18n-I18nConfiguration-addInterceptors  设置完毕");
	}
}
